//
//  RWTabBar.m
//  04-ipadQQ
//
//  Created by 紫荆秋雪 on 16/4/7.
//  Copyright © 2016年 紫荆秋雪. All rights reserved.
//

#import "RWTabBar.h"
#import "RWTabBarButton.h"

@interface RWTabBar ()

/** 选中按钮 */
@property (nonatomic,strong) RWTabBarButton *selectBtn;

@end

@implementation RWTabBar

- (instancetype)initWithFrame:(CGRect)frame{
    
    self = [super initWithFrame:frame];
    if (self) {
        
        //1、创建子控件
        RWTabBarButton *firstBtn = [self setupTabBarImageName:@"tab_bar_e_album_icon" TabBarButtonName:@"album"];
        
        //2、按钮不用时，显示出来的状态为“凹下去”
        firstBtn.enabled = NO;
        
        //设置第一个按钮为当前显示的控制器——按钮
        self.selectBtn = firstBtn;
        
        [self setupTabBarImageName:@"tab_bar_e_more_icon" TabBarButtonName:@"more"];
        
        [self setupTabBarImageName:@"tab_bar_feed_icon" TabBarButtonName:@"feed"];
        
        [self setupTabBarImageName:@"tab_bar_friend_icon" TabBarButtonName:@"friend"];
        
        [self setupTabBarImageName:@"tab_bar_passive_feed_icon" TabBarButtonName:@"feed"];
        
        [self setupTabBarImageName:@"tab_bar_pic_wall_icon" TabBarButtonName:@"wall"];

    }
    return self;
}

/**
 *  创建子控件方法
 */
- (RWTabBarButton *)setupTabBarImageName:(NSString *)imageName TabBarButtonName:(NSString *)titleName;
{
    //1、创建 控件
    RWTabBarButton *tabBarBtn = [[RWTabBarButton alloc] init];
    //2、设置图片
    [tabBarBtn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    //3、设置按钮的文字
    [tabBarBtn setTitle:titleName forState:UIControlStateNormal];
    //添加到父控件上
    [self addSubview:tabBarBtn];
    
    //4、添加监听
    [tabBarBtn addTarget:self action:@selector(tabBarBtnClick:) forControlEvents:UIControlEventTouchDown];
    
    //5、返回btn
    return tabBarBtn;
}

#pragma mark - 监听按钮的点击
- (void)tabBarBtnClick:(RWTabBarButton *)btn{

    self.selectBtn.enabled = YES;
    btn.enabled = NO;    
    self.selectBtn = btn;

    //点击按钮发出通知
    [[NSNotificationCenter defaultCenter] postNotificationName:RWTabBarDidSelectNotification object:nil userInfo:@{RWTabBarSelectIndex : @(btn.tag)}];
    
}


#pragma mark - 布局子控件
- (void)layoutSubviews
{

    [super layoutSubviews];
    NSInteger count = self.subviews.count;
    for (NSInteger i = 0; i<count; i++) {
        
        RWTabBarButton *tbBtn = self.subviews[i];
        
        //设置frame
        tbBtn.width = self.width;
        tbBtn.height = self.height * 1.0 / count;
        tbBtn.x = 0;
        tbBtn.y = i * tbBtn.height;
        
        /**
         *  给 按钮绑定tag值
         */
        tbBtn.tag = i;
        
    }
    
}


@end
